YUI.add('wfsync', function (Y) {
	var indicator = Y.one('#sync-indicator'),
		collidewarn = Y.one('#collide-warn'),
		noptimes = 0;
	
	collidewarn.on('click',function(e){
		collidewarn.hide(true);
	});
	
	var inprogress = false;
	
	var ke = (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress';
	
	Y.namespace('AppStatus');
	
	Y.on('click',function(e){
		e.preventDefault();
		var ac = e.target.get('id'); 
		if('undo-link' == ac){
			Y.AppStatus.undoStart = true;
			Y.changeHistory.undo();
		}else{
			Y.AppStatus.redoStart = true;
			Y.changeHistory.redo();
		}
	},['#undo-link','#redo-link']);
	
	Y.one(document).on('click',function(e){
		if(e.target.get('id') == 'undo-link'){
			Y.AppStatus.undoStart = true;
			Y.log('undo-link clicked');
		}else if(e.target.get('id') == 'redo-link'){
			Y.AppStatus.redoStart = true;
			Y.log('redo-link clicked');
		}else{
			Y.AppStatus.undoStart = false;
			Y.AppStatus.redoStart = false;
			Y.log('document Clicked');
		}
	});
	
	Y.one(document).on(ke,function(e){
		var keyCode = e.keyCode;
		if(e.ctrlKey){
			Y.log(keyCode);
			if(keyCode == 115 || keyCode == 83){
				e.preventDefault();
				sync(true);
			}else if(keyCode == 90 || keyCode == 122){
				if(Y.filterMode)return;
				e.preventDefault();
				if(e.shiftKey){
					Y.AppStatus.redoStart = true;
					Y.changeHistory.redo();
				}else{
					Y.AppStatus.undoStart = true;
					Y.changeHistory.undo();
				}
			}else{
				Y.AppStatus.redoStart = false;
				Y.AppStatus.undoStart = false;
			}
		}
	});
	
	indicator.on('click',function(e){
		e.preventDefault();
			sync(true);
	});
	
	Y.showSyncMsg = function(msg){
		indicator.addClass('notsync');
		indicator.setContent(msg);
		indicator.show();
	}
	
	function showMsg(msg){
		indicator.setContent(msg);
		indicator.removeClass('notsync');
		indicator.show();
	}
	
	var tH = {
            success: function(id, o, args) {
    				var r = Y.JSON.parse(o.responseText);
    				var res = r.response;
    				if(res.lastTransId){
    					Y.lastTransId = res.lastTransId;
    					if(res.collide){
    						showMsg(Y.translator.updatingView());
    						if(Y.changeHistory.syncData.length > 0){
    							collidewarn.show(true);
    						}
    						Y.processingCollide = true;
    						var collideDataArray = res.data;
    						Y.each(collideDataArray,function(d){
    							var cdarray = d.changeDelta;
    							Y.each(cdarray,function(cd){
        							if(cd.action == 'add'){
            							delete cd.mid;
            							delete cd.action;
            							if(Y.projectListList[cd.dp]){
            								Y.projectListList[cd.dp].create(cd);
            							}else{
            								Y.totalData.add(cd);
            							}
        							}else if(cd.action == 'delete'){
        								var model = Y.Wfutils.getModelById(cd.uuid);
        								if(model){
        									model.destroy();
        								}else{
        									Y.totalDataHash[cd.uuid] = null;
        								}
        							}else if(cd.action == 'modify'){
        								delete cd.action;
        								var mid = cd.mid;
        								delete cd.mid;
        								var ud = {};
        								var dpv;
        								Y.each(Y.Object.keys(cd),function(k){
        									if(k == 'dp'){
        										dpv = cd['dp'];
        									}
        									ud[k] = cd[k].newVal;
        								});
        								var m = Y.Wfutils.getModelById(mid);
        								if(m){
            								m.setAttrs(ud).save();
            								if(dpv){
            									Y.projectListList[dpv.prevVal].remove(m);
            									Y.projectListList[dpv.newVal].add(m);
            								}
        								}else{//视图中没有这个条目，是远程同步过来的。
        									var r = Y.totalDataHash[mid];
        									if(r){
            									var data = r.get('data');
            									data = Y.merge(data,ud);
            									r.set('data',data);
            									Y.totalData.update(r);
        									}
        									if(dpv){
        										Y.projectListList[dpv.newVal].create(ud);
        									}
        								}
        							}else{
        								;
        							}
    							});
    						});
    						Y.processingCollide = false;
    					}
    				}
    				showMsg(Y.translator.synced());
    				inprogress = false;
            },
            failure: function(id, o, args) {
            			showMsg('同步出错');
            			inprogress = false;
                     }
        };
        /* configuration object for transactions */
    function getQueryObject(qo){
    	return {
    		method:'POST',
            on: {
                success: tH.success,
                failure: tH.failure
            },
            data:qo,
            context: tH,
            arguments: {}
    	}
    }
    
    var timer;
    
    function sync(forceSync){
    	if(!Y.loginUser && !Y.sharedMode){
    		Y.showMsg(Y.translator.notLoginTip(),1500);
    		return;
    	}
    	Y.log('inprogress:' + inprogress);
		if(inprogress)return;
		var cl = Y.changeHistory.syncData.length; 
		if( cl == 0){
			noptimes++;
		}
		if(noptimes > 6 || forceSync || cl > 0){
			noptimes = 0;
			inprogress = true;
			Y.lastSyncData = Y.changeHistory.getSyncData();
			showMsg(Y.translator.synchronizing());
			Y.io('/smartcfud', getQueryObject({'_modelName':'com.m3958.firstgwt.server.model.WFChangeLog',
												'_operationType':'add',
												'lastTransId':Y.lastTransId,
												'mid':Y.rootEntry,
												'uid':Y.ownerUserId,
												'shared':Y.sharedMode,
												'changeDelta':Y.JSON.stringify(Y.lastSyncData)}));
		}

    }
    
    Y.mannalSync = sync;
    
    //http://www.m3958.com/smartcfud?&_modelName=com.m3958.firstgwt.server.model.WebSite&_jsonv=vv&_tz=Asia%2FShanghai&_operationType=fetch&_startRow=0&_endRow=75&_textMatchStyle=substring&_componentId=isc_ListGrid_2&_dataSource=webSiteDS&isc_metaDataPrefix=_&isc_dataFormat=json
    Y.startSync = function(){
    	if(!timer){
        	timer = Y.later(10000,Y,sync,[],true);//10秒
    	}
    };
    
    Y.stopSync = function(){
    	if(timer)timer.cancel();
    }
        
},'0.0.1',{requires:['io-base', 'json','querystring-stringify-simple','event-synthetic','node','dump']});